/**
 *
 */
package com.naiterui.ehp.bs.doctor.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.naiterui.ehp.bp.utils.lang.FirstLetterUtil;
import com.naiterui.ehp.bp.utils.sort.ABCUtil.ABCVO;

/**
 * @Description ABC工具类
 */
public class ABCUtil {

    /**
     * 26字母：<code>LETTERS</code>
     */
    private static final String[] LETTERS = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "#"};

    public static <T> List<ABCVO<T>> toABC(List<T> list, String attr) throws SecurityException,
            NoSuchFieldException,
            IllegalArgumentException,
            IllegalAccessException {
        Map<String, List<T>> map = new HashMap<>();
        for (T obj : list) {
            Class<? extends Object> clazz = obj.getClass();
            Field field = clazz.getDeclaredField(attr);
            field.setAccessible(true);
            String attrVal = field.get(obj).toString();
            String key = FirstLetterUtil.getNameFristChar(attrVal);
            List<T> subList = map.get(key);
            if (subList == null) {
                subList = new ArrayList<>();
            }
            subList.add(obj);
            map.put(key, subList);
        }
        Map<String, List<T>> linkedMap = new LinkedHashMap<>();
        for (String letter : LETTERS) {
            List<T> abcList = map.get(letter);
            if (abcList != null) {
                linkedMap.put(letter, abcList);
            }
        }
        List<ABCVO<T>> abcVO = new ArrayList<>();
        for (String k : linkedMap.keySet()) {
            ABCVO<T> abc = new ABCVO<>();
            abc.setKey(k);
            abc.setVoList(map.get(k));
            abcVO.add(abc);
        }
        return abcVO;
    }
}
